package deep.projects.newsapp.activities;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SnsAccount;
import com.umeng.socialize.bean.SocializeUser;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.wuxinwudai.android.util.StringUtils;
import com.wuxinwudai.android.util.ToastUtils;

import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import deep.projects.newsapp.R;
import deep.projects.newsapp.umeng.UmengConfig;
import deep.projects.newsapp.utils.ViewUtils;

/**
 * @author 吾心无待 于2016年03月05日
 */
public class LoginActivity extends BaseLayoutActivity {
    private UMSocialService umSocialService;//友盟第三方登录成员变量
    @BindView(R.id.et_mobile) EditText metAccount;
    @BindView(R.id.et_password) EditText metPassword;
    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    //初始化友盟服务
    private void initUmengSocialService(){
        umSocialService = UMServiceFactory.getUMSocialService(UmengConfig.OAUTH);
        umSocialService.getConfig().setSsoHandler(new SinaSsoHandler());//添加新浪登录
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(LoginActivity.this,UmengConfig.QQAppID,UmengConfig.QQAppKey);
        umqqSsoHandler.addToSocialSDK();//添加QQ登录，应用名称：新闻APPKey,AppSecret
        //UMWXHandler umwxHandler = new UMWXHandler(LoginActivity.this,"","");
        //umwxHandler.addToSocialSDK();//添加微信平台登录
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        tvTitle.setText(R.string.title_activity_login);
        initUmengSocialService();
    }
    //登录
    @OnClick(R.id.btn_login) void onLogin(){
        final String mobile = metAccount.getText().toString();
//        if(StringUtils.isNullOrWhiteSpace(mobile)){
//            ToastUtils.show(this, R.string.msg_empty_account);
//            return;
//        }
//        if (!RegexUtils.isMobile(mobile)){
//            ToastUtils.show(this, getString(R.string.msg_mobile_format_incorrect));
//            return;
//        }
//        final String password = metPassword.getText().toString();
//        if (password.length() < 6){
//            ToastUtils.show(this, getString(R.string.msg_password_length_incorrect));
//            return;
//        }
//        JSONObject obj = new JSONObject();
//        try{
//            obj.put("mobile",mobile);
//            obj.put("password",SecurityUtils.md5(password));
//        }catch (JSONException ex){
//
//        }
//        jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Urls.LOGIN_URL,obj, new Response.Listener<JSONObject>() {
//            @Override
//            public void onResponse(JSONObject s) {
//                try{
//                    JsonRequestResult jrr = JsonRequestResult.from(s);
//                    if (jrr.isOk()){
//                        NewsApplication.setUser(User.create(s.getInt("userid"),mobile));
//                        ViewUtils.goProfileActivity(LoginActivity.this);
//                        finish();
//                    }else {
//                        ToastUtils.show(LoginActivity.this,R.string.msg_account_or_password_incorrect);
//                    }
//                }catch (JSONException ex){
//                    ex.printStackTrace();
//                    ToastUtils.show(LoginActivity.this,R.string.msg_login_failed);
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//                ToastUtils.show(LoginActivity.this,volleyError.getMessage());
//            }
//        });
    }
    //取回密码
    @OnClick(R.id.tv_go_to_retrieve_password) void onGoToRetrievePassword(){ ViewUtils.goRetrievePasswordActivity(LoginActivity.this);}
    //进行注册
    @OnClick(R.id.tv_go_to_register) void onGoToRegister(){ViewUtils.goRegisterActivity(LoginActivity.this);}
    //用 QQ 账号进行登录
    @OnClick(R.id.ll_qq) void onLoginByQQ(){
        umSocialService.doOauthVerify(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(Bundle bundle, SHARE_MEDIA info) {
                umSocialService.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if(status == 200 && info != null){
                            ViewUtils.goProfileActivity(LoginActivity.this);

//                            StringBuilder sb = new StringBuilder();
//                            User u = new User();
//                            u.setGender((String)info.get("gender"));
//                            u.setAvatar((String) info.get("profile_image_url"));
//                            umSocialService.getUserInfo(LoginActivity.this, new SocializeListeners.FetchUserListener() {
//                                @Override
//                                public void onStart() {
//
//                                }
//
//                                @Override
//                                public void onComplete(int status, SocializeUser socializeUser) {
//                                    if (status == 200 && socializeUser != null) {
//                                        List<SnsAccount> snsAccounts = socializeUser.mAccounts;
//                                        SHARE_MEDIA sm = socializeUser.mDefaultPlatform;
//                                        SnsAccount ma =  socializeUser.mLoginAccount;
//                                    } else {
//                                        Log.d("TestData", "发生错误：" + status);
//                                    }
//                                }
//                            });
                            //Log.d("TestData",sb.toString());
                        }else{
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        });
    }
    //微信登录
    @OnClick(R.id.ll_wechat) void onLoginByWechat(){
        umSocialService.doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
            }
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
            }
            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                //获取相关授权信息
                umSocialService.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            StringBuilder sb = new StringBuilder();
                            Set<String> keys = info.keySet();
                            for (String key : keys) {
                                sb.append(key + "=" + info.get(key).toString() + "\r\n");
                            }
                            Log.d("TestData", sb.toString());
                        } else {
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            }
            @Override
            public void onCancel(SHARE_MEDIA platform) {

            }
        });
    }
    //新浪微博
    @OnClick(R.id.ll_weibo) void onLoginByWeibo(){
        umSocialService.doOauthVerify(LoginActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }
            @Override
            public void onComplete(Bundle bundle, SHARE_MEDIA share_media) {
                if (bundle != null && !StringUtils.isNullOrWhiteSpace(bundle.getString("uid"))) {
                    ToastUtils.showShort(LoginActivity.this, "授权成功.");
                } else {
                    ToastUtils.showShort(LoginActivity.this, "授权失败.");
                }
            }
            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {

            }
            @Override
            public void onCancel(SHARE_MEDIA share_media) {
            }
        });
    }

    //友盟回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = umSocialService.getConfig().getSsoHandler(requestCode);
        if(ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }


}
